package cn.edu.lingnan.controller;

import cn.edu.lingnan.common.Result;
import cn.edu.lingnan.entity.Contest;
import cn.edu.lingnan.entity.Prove;
import cn.edu.lingnan.entity.Users;
import cn.edu.lingnan.entity.UsersAdmin;
import cn.edu.lingnan.entity.dto.Inserttimedto;
import cn.edu.lingnan.entity.dto.LevelNumDto;
import cn.edu.lingnan.entity.dto.SelectLevelDTO;
import cn.edu.lingnan.entity.excelPojo.StudentContest;
import cn.edu.lingnan.mapper.ProveMapper;
import cn.edu.lingnan.mapper.StudentContestMapper;
import cn.edu.lingnan.mapper.UserMapper;
import cn.edu.lingnan.service.ExcelService;
import cn.edu.lingnan.service.IAdminService;
import cn.edu.lingnan.service.IContestService;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin")
public class AdminController {


    @Resource
    private IContestService contestService;

    @Resource
    private ExcelService excelService;

    @Autowired
    private StudentContestMapper studentContestMapper;

    @Autowired
    private ProveMapper proveMapper;

    @Autowired
    private IAdminService adminService;

    @Autowired
    private UserMapper userMapper;

    // 新增或者更新
    @PostMapping("/contestinfo")
    public Result save(@RequestBody Contest contest) throws ParseException {

        System.out.println(contest);
        return Result.success(contestService.saveOrUpdate(contest));
    }

    //单个删除
    @DeleteMapping("/contestinfo/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(contestService.removeById(id));
    }

    //批量删除
    @PostMapping("/contestinfo/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(contestService.removeByIds(ids));
    }

    //显示全部
    @GetMapping("/contestinfo")
    public Result findAll() {
        return Result.success(contestService.list());
    }

    // //按id查单个
    // @GetMapping("/contestinfo/{id}")
    // public Result findOne(@PathVariable Integer id){
    //     return Result.success(contestService.getById(id));
    // }

    //页码
    @GetMapping("/contestinfo/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String contestName,
                           @RequestParam(defaultValue = "") String contestType
    ) {
        QueryWrapper<Contest> queryWrapper = new QueryWrapper<>(); // 用于构建查询条件
        queryWrapper.orderByDesc("id");
        if (!"".equals(contestName)) {
            queryWrapper.like("contest_name", contestName);
        }
        if (!"".equals(contestType)) {
            queryWrapper.like("contest_type", contestType);
        }

        return Result.success(contestService.page(new Page<>(pageNum, pageSize), queryWrapper));

    }

    /**
     * 导出接口
     */
    @GetMapping("/contestinfo/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Contest> list = contestService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名

        writer.addHeaderAlias("contestName", "竞赛名称");
        writer.addHeaderAlias("contestType", "竞赛类型");
        writer.addHeaderAlias("addtime", "创建时间");
        writer.addHeaderAlias("organizer", "主办单位");
        writer.addHeaderAlias("year", "年份");


        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("比赛信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }


    @GetMapping("/awardInfo/page")
    public Result AwardInfoPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String ContestName,
                                @RequestParam(defaultValue = "") String TeamGuiderId,
                                @RequestParam(defaultValue = "") String Year,
                                @RequestParam(defaultValue = "") String TeamGuider,
                                @RequestParam(defaultValue = "") String Organizer,
                                @RequestParam(defaultValue = "") String StudentsName,
                                @RequestParam(defaultValue = "") String PriceLevel,
                                @RequestParam(defaultValue = "") String ProjectName) {

        if (Year.equals("NaN")) {
            Year = "";
        }
        QueryWrapper<StudentContest> queryWrapper = new QueryWrapper<>(); // 用于构建查询条件
        queryWrapper.orderByDesc("id");
        if (!"".equals(ContestName)) {
            queryWrapper.like("contest_name", ContestName);
        }
        if (!"".equals(TeamGuiderId)) {
            queryWrapper.like("team_guider_id", TeamGuiderId);
        }
        if (!"".equals(TeamGuider)) {
            queryWrapper.like("team_guider", TeamGuider);

        }
        if (!"".equals(PriceLevel)) {
            queryWrapper.like("price_level", PriceLevel);

        }
        if (!"".equals(ProjectName)) {
            queryWrapper.like("project_name", ProjectName);

        }
        if (!"".equals(Organizer)) {
            queryWrapper.like("Organizer", Organizer);

        }

        if (!"".equals(Year)) {
            queryWrapper.like("year", Year);

        }
        if (!"".equals(StudentsName)) {
            LambdaQueryWrapper<StudentContest> studentContestLambdaQueryWrapper = new LambdaQueryWrapper<>();


            queryWrapper.like("team_leader_name", StudentsName).or().like("other_students", StudentsName);
//            queryWrapper.like("other_students", StudentsName);


        }
        Page<StudentContest> page = excelService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);

    }

    @PostMapping("/saveaward")
    public Result saveaward(@RequestBody StudentContest studentContest) {

        System.out.println(studentContest);
        return Result.success(excelService.saveOrUpdate(studentContest));
    }


    //单个删除
    @DeleteMapping("/awardinfo/{id}")
    public Result deleteaward(@PathVariable Integer id) {
        return Result.success(excelService.removeById(id));
    }

    //批量删除
    @PostMapping("/awardinfo/del/batch")
    public Result deleteBatchaward(@RequestBody List<Integer> ids) {
        return Result.success(excelService.removeByIds(ids));
    }


    //选中比赛的逻辑，比赛列表
    @GetMapping("/AllContest")
    public List<String> finAll(@RequestParam String year) {

        LambdaQueryWrapper<StudentContest> studentContestLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentContestLambdaQueryWrapper.eq(StudentContest::getYear, year);
        studentContestLambdaQueryWrapper.select(StudentContest::getContestName)
        .isNotNull(StudentContest::getContestName);
        List<StudentContest> studentContests = studentContestMapper.selectList(studentContestLambdaQueryWrapper);

        //去掉重复数据
        List<String> list = studentContests.stream()
                .map(StudentContest::getContestName)
                .filter(ObjectUtil::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());
        System.out.println(list);
        return list;


    }

    @PostMapping("/inserttime")
    public void addtime(@RequestBody Inserttimedto data) {
        System.out.println(data);
        LambdaQueryWrapper<StudentContest> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<StudentContest> studentContests = studentContestMapper.selectList(lambdaQueryWrapper);
        for (StudentContest s : studentContests
        ) {
            if (s.getYear() == null) {
                s.setYear(data.getYear());
                studentContestMapper.updateById(s);
            }

        }


    }

    @GetMapping("/download")
    public void download(@RequestParam String AwardId, HttpServletResponse response) throws FileNotFoundException {
        LambdaQueryWrapper<Prove> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Prove::getAwardId, AwardId);
        lambdaQueryWrapper.select(Prove::getProveName);
        List<Prove> proves = proveMapper.selectList(lambdaQueryWrapper);
        System.out.println(proves.size());
        if (proves.size() != 0) {
            for (Prove file : proves
            ) {
                String proveName = file.getProveName();
                String path = System.getProperty("user.dir")+ File.separator +"DaoChu"+File.separator+ "_" + AwardId + File.separator + proveName;
                //设置相应参数
                byte[] bName = proveName.getBytes(StandardCharsets.UTF_8);
                String newName = new String(bName, StandardCharsets.ISO_8859_1);
                response.setHeader("Content-Disposition", "attachment;fileName=" + newName);
                FileInputStream fileInputStream = new FileInputStream(path);
                try {
                    BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                    byte[] b = new byte[1024];
                    int len;
                    while ((len = fileInputStream.read(b)) != -1) {
                        outputStream.write(b, 0, len);
                    }
                    fileInputStream.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }


    }

    @GetMapping("/findDonwload")
    public List<String> findAll(@RequestParam String AwardId) {
        LambdaQueryWrapper<Prove> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Prove::getAwardId, AwardId);
        lambdaQueryWrapper.select(Prove::getProveName);
        List<Prove> proves = proveMapper.selectList(lambdaQueryWrapper);
        System.out.println(proves.size());
        List<String> list = new ArrayList<>();
        if (proves.size() != 0) {
            for (Prove file : proves
            ) {
                String proveName = file.getProveName();
                String presubstring = proveName.substring(0, 11);
                String replace = proveName.replace(presubstring, "");
                System.out.println(replace);

                String substring = replace.substring(replace.lastIndexOf("."));
                System.out.println(substring);
                String replace1 = replace.replace(substring, "");
                System.out.println(replace1);
                String substring1 = replace1.substring(replace1.length() - 36);
                String fileName = replace1.replace(substring1, "");
                list.add(fileName + substring);


            }


        }
        return list;
    }

    static Integer[] total = {0, 0, 0, 0, 0, 0};

    @GetMapping("/searchTotal")
    public Result awardTotal(@RequestParam(defaultValue = "") String searchSName,
                             @RequestParam(defaultValue = "") String searchSCode,
                             @RequestParam(defaultValue = "") String searchGuider,
                             @RequestParam(defaultValue = "") String searchGuiderId,
                             @RequestParam(defaultValue = "") String searchYear) {
        LambdaQueryWrapper<StudentContest> studentContestLambdaQueryWrapper = new LambdaQueryWrapper<>();
        System.out.println(searchYear);
        if (searchYear.equals("全部")) {
            searchYear = "";
        }
        if (!searchSName.equals("")) {
            studentContestLambdaQueryWrapper.eq(StudentContest::getTeamLeaderName, searchSName).or().like(StudentContest::getOtherStudents, searchSName);
        }
        if (!searchSCode.equals("")) {
            studentContestLambdaQueryWrapper.eq(StudentContest::getTeamLeaderId, searchSCode);
        }
        if (!searchGuider.equals("")) {
            studentContestLambdaQueryWrapper.eq(StudentContest::getTeamGuider, searchGuider);
        }
        if (!searchGuiderId.equals("")) {
            studentContestLambdaQueryWrapper.eq(StudentContest::getTeamGuiderId, searchGuiderId);
        }
        if (!searchYear.equals("")) {
            studentContestLambdaQueryWrapper.eq(StudentContest::getYear, searchYear);
        }
        studentContestLambdaQueryWrapper.isNotNull(StudentContest::getPriceLevel);
        List<StudentContest> studentContests = studentContestMapper.selectList(studentContestLambdaQueryWrapper);
        System.out.println(studentContests);
        List<String> AllLevel = new ArrayList<>();

        for (StudentContest s : studentContests
        ) {
            String priceLevel = s.getPriceLevel();
            AllLevel.add(priceLevel);

        }
        total = new Integer[]{0, 0, 0, 0, 0, 0};
        Integer[] country = {0, 0, 0, 0, 0, 0};
        Integer[] province = {0, 0, 0, 0, 0, 0};
        Integer[] school = {0, 0, 0, 0, 0, 0};
        Integer[] college = {0, 0, 0, 0, 0, 0};
        Integer other = 0;
        List<Integer[]> allNum = new ArrayList<>();


        for (String level : AllLevel
        ) {
            if (level.contains("国家")) {
                country = num(country, level);
            } else if (level.contains("省")) {
                province = num(province, level);
            } else if (level.contains("校")) {
                school = num(school, level);
            } else if (level.contains("院")) {
                college = num(college, level);
            } else {
                other += 1;
            }


        }
        allNum.add(country);
        allNum.add(province);
        allNum.add(school);
        allNum.add(college);
        allNum.add(total);
        int flag = 0;
        List<LevelNumDto> list = new ArrayList<>();
        for (Integer[] a : allNum
        ) {
            LevelNumDto dto = new LevelNumDto();
            System.out.println(Arrays.toString(a));

            if (flag == 0) {
                dto.setLevel("国家级");
            }
            if (flag == 1) {
                dto.setLevel("省级");
            }
            if (flag == 2) {
                dto.setLevel("校级");
            }
            if (flag == 3) {
                dto.setLevel("院级");
            }
            if (flag == 4) {
                dto.setLevel("总计");
            }

            dto.setCPrice1(a[0]);
            dto.setCPrice2(a[1]);
            dto.setCPrice3(a[2]);
            dto.setCPrice4(a[3]);
            dto.setCPrice5(a[4]);
            dto.setCPrice6(a[5]);
            list.add(dto);
            flag++;
        }
        System.out.println(list);
        String s = other.toString();
        System.out.println(other);
        System.out.println(s);


        return Result.success(list, s);
    }

    @PostMapping("/insertA")
    public Result insertAward(@RequestBody StudentContest studentContest) {
        System.out.println(studentContest);
        studentContest.setId((long) (excelService.count() + 1));
        studentContestMapper.insert(studentContest);
        return Result.success(excelService.count());
    }


    //单个删除
    @DeleteMapping("/adminUser/{id}")
    public Result deleteAdmin(@PathVariable Integer id) {
        return Result.success(adminService.removeById(id));
    }



    private Integer[] num(Integer[] num, String level) {
        if (level.contains("一")) {
            num[0] += 1;
            total[0] += 1;
        } else if (level.contains("二")) {
            num[1] += 1;
            total[1] += 1;
        } else if (level.contains("三")) {
            num[2] += 1;
            total[2] += 1;
        } else if (level.contains("金")) {
            num[3] += 1;
            total[3] += 1;
        } else if (level.contains("银")) {
            num[4] += 1;
            total[4] += 1;
        } else if (level.contains("铜")) {
            num[5] += 1;
            total[5] += 1;
        }else {
            throw new RuntimeException("请检查获奖级别是否有正确填写");
        }
        return num;
    }

    @PostMapping("/selectLevel")
    @ApiOperation("获奖页面用来选中评级接口")
    public Result selectLevel(@RequestBody SelectLevelDTO dto){
        try {
            return excelService.selectLevel(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改失败");
        }
    }

    /**
     * 模板下载
     */
    @GetMapping("/getModle")
    @ApiOperation(value = "模板下载接口")
    public void getModle(HttpServletResponse response){
        excelService.getModle(response);
    }



}